package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractBaseTiktokApiHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据订单号下载订单详情
 * <p>
 * cy.salesOrder.download.byOrderId
 * /order/202309/orders (指定单号下载订单) https://partner.tiktokshop.com/docv2/page/650aa8ccc16ffe02b8f167a0?external_id=650aa8ccc16ffe02b8f167a0#Back%20To%20Top
 * </p>
 *
 * @author gywang
 * @since 2024-07-22
 */
@Slf4j
@Service
public class TiktokSalesOrderDownloadByIdService extends AbstractBaseTiktokApiHandler<OrderGetDTO> {

	private static final String SHOP_ORDER_DETAIL = "orders";
	/**
	 * 每批次单号数量最大值
	 */
	private static final int downloadBatch = 50;

	@Override
	public String getTiktokMethod() {
		return TiktokApiConstant.DOWNLOAD_ORDER_DETAIL;
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_ORDERID;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		// 参数校验
		Result<?> result = checkParams(platformApiParamDTO, orderGetDTO);
		if (result.hasError()) {
			return result;
		}
		List<Object> list = new ArrayList<>();
		String[] orderCodeArr = orderGetDTO.getOrderId().split(",");

		if (orderCodeArr.length > 0) {
			for (String id : orderCodeArr) {
				result = this.getOrderById(platformApiParamDTO, id);
				if (result.hasError()) {
					return result;
				}
				Object data = result.getData();
				// 同步返回
				if (orderGetDTO.getIsAsync() == 0) {
					list.add(data);
				} else {
					platformApiParamDTO.setPlatformIdentifierTag(id);
					result = this.sendRequestToPlatform(platformApiParamDTO, data, true);
					if (!result.isSuccess()) {
						return result;
					}
				}
			}
		}
		// 同步返回
		if (orderGetDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();
	}


	/**
	 * 根据id获取订单
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return
	 */
	public Result<?> getOrderById(PlatformApiParamDTO platformApiParamDTO, String id) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.getOrderBySdk(platformApiParamDTO, id);
	}


	/**
	 * 执行api请求
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return 请求结果 resultMap.get(DATA_FIELD)
	 */
	public Result<?> getOrderBySdk(PlatformApiParamDTO platformApiParamDTO, String id) {
		Map<String, Object> params = new HashMap<>();
		params.put("shop_cipher", getShopCipher(platformApiParamDTO));
		params.put("ids", id);
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		String requestId = platformApiParamDTO.getRequestId();
		Result<?> result = this.executeTiktokApi(getDefaultUrl(storeConfig), storeConfig, params, null, requestId, TiktokApiConstant.ApiHttpMethod.GET);
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> saleData = (Map<String, Object>) resultMap.get(DATA_FIELD);
		if (CollUtil.isEmpty(saleData)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, requestId, id);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		Map<String, Object> saleMap = Convert.toMap(String.class, Object.class, saleData);
		List orders = MapUtil.get(saleMap, "orders", List.class);
		if (CollUtil.isEmpty(orders)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, platformApiParamDTO.getRequestId(), id);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}


		return Result.success().addData(saleData);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param orderGetDTO         接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		if (orderGetDTO == null || platformApiParamDTO.getStoreConfig() == null || StrUtil.isBlank(orderGetDTO.getOrderId())) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), orderGetDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
